<template>
  <view class="group-manage-container">
    <!-- 页面头部 -->
    <view class="page-header">
      <button class="back-btn" @click="goBack">← 返回</button>
      <div class="page-title">分组管理</div>
    </view>

    <!-- 房间信息 -->
    <view class="room-info-section">
      <div class="card">
        <div class="card-header">
          <div class="title">房间信息</div>
        </div>
        <div class="info-content">
          <div class="info-row">
            <div class="info-label">房间名称:</div>
            <div class="info-value">{{ roomName }}</div>
          </div>
          <div class="info-row">
            <div class="info-label">房间ID:</div>
            <div class="info-value">{{ roomId }}</div>
          </div>
          <div class="info-row">
            <div class="info-label">分组数量:</div>
            <div class="info-value group-count">{{ groupList.length }} 个</div>
          </div>
        </div>
      </div>
    </view>

    <!-- 分组列表 -->
    <view class="group-list-section">
      <div class="card">
        <div class="card-header">
          <div class="title">分组列表</div>
          <div class="header-actions">
            <button class="create-btn" @click="showCreateModal">创建分组</button>
            <button class="refresh-btn" @click="loadGroupList" :disabled="loading">
              {{ loading ? '刷新中...' : '刷新' }}
            </button>
          </div>
        </div>
        
        <div v-if="loading" class="loading-container">
          <div class="loading-spinner"></div>
          <text>加载中...</text>
        </div>
        
        <div v-else-if="groupList.length === 0" class="empty-state">
          <text>暂无分组</text>
        </div>
        
        <div v-else class="group-list">
          <div 
            class="group-item" 
            v-for="group in groupList" 
            :key="group.id"
          >
            <div class="group-header">
              <div class="group-id">分组ID: {{ group.id }}</div>
              <div class="group-status" :class="getStatusClass(group.delFlag)">
                {{ getStatusText(group.delFlag) }}
              </div>
            </div>
            
            <div class="group-info">
              <div class="info-row">
                <div class="info-label">分组名称:</div>
                <div class="info-value">{{ group.name }}</div>
              </div>
              <div class="info-row">
                <div class="info-label">分组标签:</div>
                <div class="info-value">{{ group.tag || '无' }}</div>
              </div>
              <div class="info-row">
                <div class="info-label">房间ID:</div>
                <div class="info-value">{{ group.matchRoomId }}</div>
              </div>
              <div class="info-row">
                <div class="info-label">创建时间:</div>
                <div class="info-value">{{ formatDate(group.createTime) }}</div>
              </div>
              <div class="info-row">
                <div class="info-label">更新时间:</div>
                <div class="info-value">{{ formatDate(group.updateTime) }}</div>
              </div>
            </div>
            
            <div class="group-actions">
              <button class="edit-btn" @click="editGroup(group)">编辑</button>
              <button class="delete-btn" @click="deleteGroup(group)">删除</button>
            </div>
          </div>
        </div>
      </div>
    </view>

    <!-- 创建/编辑分组模态框 -->
    <view class="modal-overlay" v-if="showModal" @click="closeModal">
      <view class="modal-content" @click.stop>
        <view class="modal-header">
          <text class="modal-title">{{ isEdit ? '编辑分组' : '创建分组' }}</text>
          <button class="close-btn" @click="closeModal">×</button>
        </view>
        
        <view class="modal-body">
          <view class="form-item">
            <text class="form-label">分组名称 *</text>
            <input 
              class="form-input" 
              v-model="formData.name" 
              placeholder="请输入分组名称，如：A组、B组"
              maxlength="50"
            />
          </view>
          
          <view class="form-item">
            <text class="form-label">分组标签</text>
            <input 
              class="form-input" 
              v-model="formData.tag" 
              placeholder="请输入分组标签，如：group_a、group_b"
              maxlength="50"
            />
          </view>
        </view>
        
        <view class="modal-footer">
          <button class="cancel-btn" @click="closeModal">取消</button>
          <button class="submit-btn" @click="submitForm" :disabled="submitting">
            {{ submitting ? '提交中...' : (isEdit ? '更新' : '创建') }}
          </button>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { MatchRoomGroupAPI } from '@/api/battle.js'

// 响应式数据
const loading = ref(false)
const submitting = ref(false)
const roomId = ref('')
const roomName = ref('')
const groupList = ref([])

// 模态框相关
const showModal = ref(false)
const isEdit = ref(false)
const formData = ref({
  matchRoomGroupId: '',
  matchRoomId: '',
  name: '',
  tag: ''
})

// 状态映射
const statusMap = {
  0: '有效',
  1: '已删除'
}

const statusClassMap = {
  0: 'status-valid',
  1: 'status-deleted'
}

// 获取状态文本
const getStatusText = (delFlag) => statusMap[delFlag] || '未知'

// 获取状态样式
const getStatusClass = (delFlag) => statusClassMap[delFlag] || 'status-unknown'

// 格式化日期
const formatDate = (timestamp) => {
  if (!timestamp) return '未设置'
  const date = new Date(timestamp)
  return date.toLocaleString('zh-CN')
}

// 加载分组列表
const loadGroupList = async () => {
  if (!roomId.value) return
  
  loading.value = true
  try {
    console.log('加载分组列表，房间ID:', roomId.value)
    
    const result = await MatchRoomGroupAPI.page({
      matchRoomId: roomId.value,
      pageNum: 0,
      pageSize: 100
    })
    
    console.log('分组列表API返回结果:', result)
    
    if (result.code === 0) {
      groupList.value = result.data || []
      console.log('获取到分组列表:', groupList.value)
    } else {
      groupList.value = []
      throw new Error(result.msg || '获取分组列表失败')
    }
  } catch (error) {
    console.error('获取分组列表失败:', error)
    uni.showToast({
      title: error.message || '获取分组列表失败',
      icon: 'none'
    })
  } finally {
    loading.value = false
  }
}

// 显示创建模态框
const showCreateModal = () => {
  isEdit.value = false
  resetForm()
  showModal.value = true
}

// 编辑分组
const editGroup = (group) => {
  isEdit.value = true
  formData.value = {
    matchRoomGroupId: group.id,
    matchRoomId: group.matchRoomId,
    name: group.name || '',
    tag: group.tag || ''
  }
  showModal.value = true
}

// 删除分组
const deleteGroup = (group) => {
  uni.showModal({
    title: '确认删除',
    content: `确定要删除分组 "${group.name}" 吗？`,
    success: async (res) => {
      if (res.confirm) {
        try {
          const result = await MatchRoomGroupAPI.remove({
            matchRoomGroupId: group.id
          })
          
          if (result.code === 0) {
            uni.showToast({
              title: '删除成功',
              icon: 'success'
            })
            loadGroupList()
          } else {
            throw new Error(result.msg || '删除失败')
          }
        } catch (error) {
          console.error('删除分组失败:', error)
          uni.showToast({
            title: error.message || '删除失败',
            icon: 'none'
          })
        }
      }
    }
  })
}

// 关闭模态框
const closeModal = () => {
  showModal.value = false
  resetForm()
}

// 重置表单
const resetForm = () => {
  formData.value = {
    matchRoomGroupId: '',
    matchRoomId: roomId.value,
    name: '',
    tag: ''
  }
}

// 提交表单
const submitForm = async () => {
  // 表单验证
  if (!formData.value.name.trim()) {
    uni.showToast({
      title: '请输入分组名称',
      icon: 'none'
    })
    return
  }
  
  submitting.value = true
  try {
    const api = isEdit.value ? MatchRoomGroupAPI.edit : MatchRoomGroupAPI.create
    const submitData = { ...formData.value }
    
    console.log('提交数据:', submitData)
    console.log('是否为编辑模式:', isEdit.value)
    
    const result = await api(submitData)
    
    console.log('API返回结果:', result)
    
    if (result.code === 0) {
      uni.showToast({
        title: isEdit.value ? '更新成功' : '创建成功',
        icon: 'success'
      })
      closeModal()
      loadGroupList()
    } else {
      throw new Error(result.msg || (isEdit.value ? '更新失败' : '创建失败'))
    }
  } catch (error) {
    console.error('提交表单失败:', error)
    uni.showToast({
      title: error.message || (isEdit.value ? '更新失败' : '创建失败'),
      icon: 'none'
    })
  } finally {
    submitting.value = false
  }
}

// 返回上一页
const goBack = () => {
  uni.navigateBack()
}

// 页面加载
onLoad((options) => {
  if (options.roomId) {
    roomId.value = options.roomId
  }
  if (options.roomName) {
    roomName.value = decodeURIComponent(options.roomName)
  }
})

// 页面挂载时加载数据
onMounted(() => {
  loadGroupList()
})
</script>

<style lang="scss" scoped>
.group-manage-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 40rpx;
}

// 页面头部样式
.page-header {
  display: flex;
  align-items: center;
  padding: 20rpx 0;
  margin-bottom: 30rpx;
  border-bottom: 1rpx solid rgba(255, 255, 255, 0.2);
  
  .back-btn {
    background: none;
    border: none;
    color: #fff;
    font-size: 28rpx;
    padding: 10rpx 20rpx;
    margin-right: 20rpx;
  }
  
  .page-title {
    font-size: 36rpx;
    font-weight: bold;
    color: #fff;
  }
}

// 房间信息样式
.room-info-section {
  margin-bottom: 30rpx;
  
  .card {
    background: rgba(255, 255, 255, 0.95);
    border-radius: 20rpx;
    padding: 30rpx;
    box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.2);
    
    .card-header {
      margin-bottom: 20rpx;
      
      .title {
        font-size: 32rpx;
        font-weight: bold;
        color: #333;
      }
    }
    
    .info-content {
      .info-row {
        display: flex;
        margin-bottom: 15rpx;
        font-size: 26rpx;
        
        .info-label {
          width: 160rpx;
          color: #666;
          font-weight: 500;
        }
        
        .info-value {
          flex: 1;
          color: #333;
          
          &.group-count {
            color: #667eea;
            font-weight: bold;
          }
        }
      }
    }
  }
}

// 分组列表样式
.group-list-section {
  .card {
    background: rgba(255, 255, 255, 0.95);
    border-radius: 20rpx;
    padding: 30rpx;
    box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.2);
    
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20rpx;
      
      .title {
        font-size: 32rpx;
        font-weight: bold;
        color: #333;
      }
      
      .header-actions {
        display: flex;
        gap: 15rpx;
        
        .create-btn {
          height: 50rpx;
          padding: 0 20rpx;
          background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
          border: none;
          border-radius: 8rpx;
          color: #fff;
          font-size: 24rpx;
          font-weight: bold;
        }
        
        .refresh-btn {
          height: 50rpx;
          padding: 0 20rpx;
          background: linear-gradient(135deg, #007bff 0%, #0056b3 100%);
          border: none;
          border-radius: 8rpx;
          color: #fff;
          font-size: 24rpx;
          
          &:disabled {
            opacity: 0.6;
          }
        }
      }
    }
    
    .loading-container, .empty-state {
      text-align: center;
      padding: 40rpx;
      color: #666;
      
      .loading-spinner {
        width: 60rpx;
        height: 60rpx;
        border: 4rpx solid #f3f3f3;
        border-top: 4rpx solid #667eea;
        border-radius: 50%;
        animation: spin 1s linear infinite;
        margin: 0 auto 20rpx;
      }
    }
    
    .group-list {
      .group-item {
        background: #f8f9fa;
        border-radius: 12rpx;
        padding: 20rpx;
        margin-bottom: 15rpx;
        border: 1rpx solid #e9ecef;
        
        .group-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 15rpx;
          
          .group-id {
            font-size: 28rpx;
            font-weight: bold;
            color: #333;
          }
          
          .group-status {
            padding: 6rpx 16rpx;
            border-radius: 16rpx;
            font-size: 22rpx;
            font-weight: bold;
            
            &.status-valid {
              background: #d4edda;
              color: #155724;
            }
            
            &.status-deleted {
              background: #f8d7da;
              color: #721c24;
            }
          }
        }
        
        .group-info {
          margin-bottom: 15rpx;
          
          .info-row {
            display: flex;
            margin-bottom: 8rpx;
            font-size: 24rpx;
            
            .info-label {
              width: 140rpx;
              color: #666;
            }
            
            .info-value {
              flex: 1;
              color: #333;
            }
          }
        }
        
        .group-actions {
          display: flex;
          gap: 10rpx;
          
          .edit-btn, .delete-btn {
            flex: 1;
            height: 50rpx;
            border: none;
            border-radius: 8rpx;
            font-size: 24rpx;
            
            &.edit-btn {
              background: #007bff;
              color: #fff;
            }
            
            &.delete-btn {
              background: #dc3545;
              color: #fff;
            }
          }
        }
      }
    }
  }
}

// 模态框样式
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
  
  .modal-content {
    width: 90%;
    max-height: 80%;
    background: #fff;
    border-radius: 20rpx;
    overflow: hidden;
    
    .modal-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 30rpx;
      border-bottom: 2rpx solid #eee;
      
      .modal-title {
        font-size: 32rpx;
        font-weight: bold;
        color: #333;
      }
      
      .close-btn {
        width: 60rpx;
        height: 60rpx;
        border: none;
        background: none;
        font-size: 40rpx;
        color: #999;
      }
    }
    
    .modal-body {
      padding: 30rpx;
      
      .form-item {
        margin-bottom: 30rpx;
        
        .form-label {
          display: block;
          font-size: 28rpx;
          color: #333;
          margin-bottom: 15rpx;
          font-weight: bold;
        }
        
        .form-input {
          width: 100%;
          height: 80rpx;
          border: 2rpx solid #eee;
          border-radius: 12rpx;
          padding: 0 20rpx;
          font-size: 28rpx;
          background: #fff;
          box-sizing: border-box;
        }
      }
    }
    
    .modal-footer {
      display: flex;
      gap: 20rpx;
      padding: 30rpx;
      border-top: 2rpx solid #eee;
      
      .cancel-btn, .submit-btn {
        flex: 1;
        height: 80rpx;
        border: none;
        border-radius: 12rpx;
        font-size: 28rpx;
        font-weight: bold;
        
        &.cancel-btn {
          background: #f8f9fa;
          color: #666;
          border: 2rpx solid #eee;
        }
        
        &.submit-btn {
          background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
          color: #fff;
          
          &:disabled {
            opacity: 0.6;
          }
        }
      }
    }
  }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
</style> 